import { useNavigate, useLocation } from 'react-router-dom';
import { useState, useEffect } from 'react';

/**
 * 通用的菜单路由处理Hook
 * @param {Array} menuList - 菜单列表
 * @param {string} modulePath - 模块路径前缀，如 '/videoEdit' 或 '/audioEdit'
 * @returns {Object} 包含路由处理函数和状态
 */
export const useMenuRouter = (menuList, modulePath) => {
  const navigate = useNavigate();
  const location = useLocation();
  const [activeMenuKey, setActiveMenuKey] = useState(null);
  
  // 监听路由变化，更新激活的菜单项
  useEffect(() => {
    if (!modulePath || !menuList) return;
    
    const pathSegments = location.pathname.split('/');
    const routeKey = pathSegments[pathSegments.length - 1];
    
    // 检查是否有匹配当前路由的菜单项
    let hasMatchedRoute = false;
    for (const parentItem of menuList) {
      if (parentItem.children?.some((child) => child.key === routeKey)) {
        hasMatchedRoute = true;
        setActiveMenuKey(routeKey);
        break;
      }
    }
    
    // 如果没有匹配的路由，默认激活第一个菜单项
    if (!hasMatchedRoute && menuList.length > 0 && menuList[0].children && menuList[0].children.length > 0) {
      const defaultKey = menuList[0].children[0].key;
      setActiveMenuKey(defaultKey);
      
      // 如果当前路由不是默认路由，执行跳转
      const defaultRoute = `${modulePath}/${defaultKey}`;
      if (location.pathname !== defaultRoute) {
        navigate(defaultRoute);
      }
    }
  }, [location.pathname, navigate, modulePath, menuList]);
  
  /**
   * 跳转到指定菜单项
   * @param {Object} menuItem - 菜单项
   * @returns {void}
   */
  const navigateToMenu = (menuItem) => {
    const targetRoute = `${modulePath}/${menuItem.key}`;
    if (location.pathname !== targetRoute) {
      navigate(targetRoute);
    }
    setActiveMenuKey(menuItem.key);
  };
  
  /**
   * 检查菜单项是否为激活状态
   * @param {string} menuKey - 菜单项key
   * @returns {boolean} 是否激活
   */
  const isMenuActive = (menuKey) => {
    return activeMenuKey === menuKey;
  };
  
  return {
    navigateToMenu,
    isMenuActive,
    activeMenuKey,
    setActiveMenuKey,
    location,
    navigate
  };
};

/**
 * 更新菜单列表的激活状态
 * @param {Array} menuList - 原始菜单列表
 * @param {string} activeKey - 激活的菜单项key
 * @returns {Array} 更新后的菜单列表
 */
export const updateMenuActiveState = (menuList, activeKey) => {
  if (!menuList || !activeKey) return menuList;
  
  return menuList.map((parentItem) => ({
    ...parentItem,
    children: parentItem.children?.map((child) => ({
      ...child,
      active: child.key === activeKey,
    })),
  }));
};